import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_app/api/user.dart';

class ProductSelect extends StatefulWidget {
  final Function onChange;

  ProductSelect({Key key, this.onChange}) : super(key: key);

  _ProductSelectState createState() => _ProductSelectState();
}

class _ProductSelectState extends State<ProductSelect> {
  final TextStyle _fieldKey = TextStyle(color: Color(0xFF666666), fontSize: 16);
  var _amounts = [];

  int _selectAmount = 0;

  int _selectTenor = 0;

  var _tenorList = [];

  Map allProducts = {};

  bool hadInit = false;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        _renderRadioAmount(context),
        _renderRadioTime(context),
      ],
    );
  }

  Container _renderRadioTime(BuildContext context) {
    return Container(
      color: Colors.white,
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('Loan Plan', style: _fieldKey),
          Container(
            margin: EdgeInsets.symmetric(vertical: 10),
            child: Wrap(
                runSpacing: 10,
                spacing: 10,
                alignment: WrapAlignment.start,
                children: _getOutlineButtonForTime()),
          )
        ],
      ),
    );
  }

  Container _renderRadioAmount(BuildContext context) {
    return Container(
      color: Colors.white,
      width: MediaQuery.of(context).size.width,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text('Loan Amount', style: _fieldKey),
          Container(
            margin: EdgeInsets.symmetric(vertical: 10),
            child: Wrap(
                runSpacing: 10,
                spacing: 10,
                alignment: WrapAlignment.start,
                children: _getOutlineButtonForAmount()),
          )
        ],
      ),
    );
  }

  List<Widget> _getOutlineButtonForAmount() {
    List<Container> children = [];
    for (int i = 0; i < _amounts.length; i++) {
      var item = _amounts[i];
      children.add(Container(
        width: 80,
        child: MaterialButton(
          elevation: 0,
          shape: RoundedRectangleBorder(
              side: BorderSide(
                  color: item['available']
                      ? int.parse(item['amount']) == _selectAmount
                          ? Colors.blue
                          : Color(0xFF929292)
                      : Color(0xFFc5cad5),
                  width: 1.0),
              borderRadius: BorderRadius.all(Radius.circular(20.0))),
          color: int.parse(item['amount']) == _selectAmount
              ? Colors.blue
              : Colors.white,
          child: Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[Text(item['amount'])],
              )),
          textColor: item['available']
              ? int.parse(item['amount']) == _selectAmount
                  ? Colors.white
                  : Color(0xFF929292)
              : Color(0xFFc5cad5),
          onPressed: () =>
              {item['available'] ? loanAmountChange(item['amount']) : null},
        ),
      ));
    }
    return children;
  }

  List<Widget> _getOutlineButtonForTime() {
    List<Container> children = [];
    for (int i = 0; i < _tenorList.length; i++) {
      var item = _tenorList[i];
      if (item['amount'].toInt() == _selectAmount) {
        children.add(Container(
          width: 100,
          child: MaterialButton(
            elevation: 0,
            shape: RoundedRectangleBorder(
                side: BorderSide(
                    color: item['available']
                        ? item['tenor'] == _selectTenor
                            ? Colors.blue
                            : Color(0xFF929292)
                        : Color(0xFFc5cad5),
                    width: 1.0),
                borderRadius: BorderRadius.all(Radius.circular(20.0))),
            color: item['tenor'] == _selectTenor ? Colors.blue : Colors.white,
            child: Padding(
                padding: EdgeInsets.symmetric(vertical: 10.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('${item['tenor']}'),
                    Padding(
                      child: Text(item['tenorUnit'].toLowerCase()),
                      padding: EdgeInsets.only(left: 5),
                    ),
                    Text('s')
                  ],
                )),
            textColor: item['available']
                ? item['tenor'] == _selectTenor
                    ? Colors.white
                    : Color(0xFF929292)
                : Color(0xFFc5cad5),
            onPressed: () =>
                item['available'] ? loanTimeChange(item['tenor']) : null,
          ),
        ));
      }
    }
    return children;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    if (hadInit) {
      return;
    }
    hadInit = true;

    Future.delayed(Duration(milliseconds: 0), () async {
      var products = await UserApi.getProducts(context);

      setState(() {
        _amounts.clear();
        _tenorList.clear();
        allProducts = products;
        products.forEach((key, value) {
          bool flag = false;
          value.forEach((val) {
            if (val['available']) {
              flag = true;
              _selectAmount = val['amount'].toInt();
              _selectTenor = val['tenor'];
              _setCurrentProduct(
                  val['amount'].toInt().toString(), val['tenor']);
            }
          });
          _amounts.add({"amount": key, "available": flag});
          _tenorList.addAll(value);
        });
      });
    });
  }

  void loanAmountChange(String amount) {
    allProducts[amount].forEach((value) => {
          if (value['tenor'] != _selectTenor && value['available'])
            {
              setState(() {
                _selectTenor = value['tenor'];
              })
            }
        });
    _setCurrentProduct(amount, _selectTenor);
    setState(() {
      _selectAmount = int.parse(amount);
    });
  }

  void loanTimeChange(int tenor) {
    _setCurrentProduct(_selectAmount.toString(), tenor);
    setState(() {
      _selectTenor = tenor;
    });
  }

  void _setCurrentProduct(String amount, int tenor) {
    Map obj = new Map();
    if (allProducts[amount] != null) {
      allProducts[amount].forEach((value) => {
            if (value['tenor'] == tenor) {obj.addAll(value)}
          });
    }
    widget.onChange(obj);
  }
}
